package com.gitee.feizns.explore.data_structure.visual.frame.bubble;

import com.gitee.feizns.explore.data_structure.visual.frame.Utils;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.Random;
import java.util.stream.Stream;

/**
 * @author feizns
 * @since 2020/1/2
 */
public class Controller {

    public static void main(String[] args) {
        Random r = new Random();
        System.out.println(r.nextInt(12));
        EventQueue.invokeLater(() -> {
            View view = new View(Controller::draw);
            for (int i = 0; i < circles.length; i++)
                circles[i] = Circle.random(view, 50);
            view.addMouseListener(new MouseLister(view));
            view.addKeyListener(new KeyLister(view));
            view.start();
        });
    }

    static Circle[] circles = new Circle[10];

    public static void draw(Graphics2D g) {
        g = Utils.init(g);
        for (Circle circle : circles) {
            if ( circle.getFill() )
                g.fill(circle.toEllipse());
            else
                g.draw(circle.toEllipse());
            circle.move();
        }
    }

    static class KeyLister extends KeyAdapter {
        View view;
        public KeyLister(View view) { this.view = view; }
        @Override
        public void keyPressed(KeyEvent e) {
            if ( e.getExtendedKeyCode() == ' ' )
                view.switchStatus();
        }
    }

    static class MouseLister extends MouseAdapter {
        View view;
        public MouseLister(View view) { this.view = view; }
        @Override
        public void mousePressed(MouseEvent e) {
            e.translatePoint(0, -(view.getBounds().height - view.getRootPane().getHeight()));
            pointCircle(e.getPoint()).forEach(Circle::changeFill);
        }
    }

    private static Stream<Circle> pointCircle(Point point) {
        return Arrays.stream(circles).filter(c -> c.inCircle(point));
    }

}
